<template>
	<div class="system-add-user-container">
		<el-dialog v-model="dialog" :title="state.form.id ? '修改用户' : '新增用户'" width="60%" :before-close="handleClose">
			<el-form ref="formRef" :model="state.form" label-width="120px" :rules="state.rules">
				<el-row>
					<el-col :span="12" class="mb20">
						<el-form-item label="用户昵称" prop="nikeName">
							<el-input v-model="state.form.nikeName"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12" class="mb20">
						<el-form-item label="手机号码" prop="phone">
							<el-input v-model="state.form.phone" maxlength="11" :disabled="state.form.id" show-word-limit></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12" class="mb20">
						<el-form-item label="用户名" prop="username">
							<el-input v-model="state.form.username" :disabled="state.form.id"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12" class="mb20">
						<el-form-item label="密码" prop="password">
							<el-input v-model="state.form.password" type="password" :disabled="state.form.id"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12" class="mb20">
						<el-form-item label="部门" prop="deptId">
							<el-tree-select
								style="width: 100%"
								v-model="state.form.deptId"
								:data="state.deptList"
								check-strictly
								:props="defaultProps"
								:render-after-expand="false"
								node-key="id"
							></el-tree-select>
						</el-form-item>
					</el-col>
					<el-col :span="12" class="mb20">
						<el-form-item label="状态" prop="status">
							<el-radio-group v-model="state.form.status">
								<el-radio v-for="item in status" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="12" class="mb20">
						<el-form-item label="类型" prop="type">
							<el-radio-group v-model="state.form.type">
								<el-radio label="0">系统主账户</el-radio>
								<el-radio label="1">店铺账号</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="12" class="mb20" v-if="state.form.type == '1'">
						<el-form-item label="店铺" prop="shopId">
							<select-shop ref="selectShopRef" v-model="state.form.shopId" @shopChange="shopChange"></select-shop>
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item label="角色权限" prop="roles">
					<el-checkbox-group v-model="state.form.roles">
						<el-checkbox v-for="(item, index) in state.roleList" :key="index" :label="item.id">{{ item.roleName }}</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
				<el-form-item label="头像" prop="avatar">
					<el-upload
						class="avatar-uploader"
						:action="action"
						:headers="headers"
						:show-file-list="false"
						:before-upload="beforeUpload"
						:on-success="handleSuccess"
						:on-error="handleError"
					>
						<img v-if="state.form.avatar" :src="state.form.avatar" class="avatar" />
						<el-icon class="avatar-uploader-icon" v-else> <ele-Plus /> </el-icon>
					</el-upload>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleClose">关 闭</el-button>
					<el-button type="primary" :loading="loading" @click="submitForm(formRef)">确 认</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts" setup>
import { defineAsyncComponent, ref, reactive } from 'vue';
import { addObj, editObj, getById } from '/@/api/upms/sysuser';
import { getList as getRoleList } from '/@/api/upms/sysrole';
import { getTreeList } from '/@/api/upms/sysdept';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { Session } from '/@/utils/storage';
import type { UploadProps } from 'element-plus';
import { useDict } from '/@/utils/dict';
interface UserSate {
	rules: object;
	form: {
		id: undefined;
		password: string;
		deptId: string;
		username: string;
		phone: string;
		nikeName: string;
		avatar: string;
		roles: Array<string>;
		shopName: string;
		shopId: string;
		type: string;
		status: string;
	};
	roleList: any;
	deptList: any;
}
// 字典
const { status } = useDict('status');
const emit = defineEmits(['initPage']);
const SelectShop = defineAsyncComponent(() => import('/@/components/selectShop/index.vue'));
const state = reactive<UserSate>({
	form: {
		id: undefined,
		password: '',
		deptId: '',
		username: '',
		phone: '',
		nikeName: '',
		avatar: '',
		roles: [],
		shopName: '',
		shopId: '',
		type: '',
		status: '0',
	},
	rules: {
		nikeName: [
			{
				required: true,
				message: '请输入用户昵称',
				trigger: 'change',
			},
		],
		phone: [
			{
				required: true,
				message: '请输入手机号码',
				trigger: 'change',
			},
		],
		username: [
			{
				required: true,
				message: '请输入用户名',
				trigger: 'change',
			},
		],
		password: [
			{
				required: true,
				message: '请输入密码',
				trigger: 'change',
			},
		],
		status: [
			{
				required: true,
				message: '请选择状态',
				trigger: 'change',
			},
		],
		roles: [
			{
				required: true,
				message: '请选择角色',
				trigger: 'change',
			},
		],
		deptId: [
			{
				required: true,
				message: '请选择部门',
				trigger: 'change',
			},
		],
		avatarArray: [
			{
				required: true,
				message: '请上传头像',
				trigger: 'change',
			},
		],
		shopId: [
			{
				required: true,
				message: '请选择店铺',
				trigger: 'change',
			},
		],
	},
	roleList: [],
	deptList: [],
});
const dialog = ref(false);
const loading = ref(false);
const formRef = ref();
const headers = {
	satoken: Session.get('token'),
};
const action = '/upms/file/upload?fileType=image';
const defaultProps = {
	children: 'children',
	label: 'name',
};
const initForm = (row: any | undefined) => {
	dialog.value = true;
	if (row && row.id) {
		getDetail(row.id);
	}

	handleRoleList();
	handleDeptList();
};
const getDetail = (id: string) => {
	loading.value = true;
	getById(id).then((response: any) => {
		state.form = response.data.data;
		loading.value = false;
	});
};
/**
 * 关闭事件
 */
const handleClose = () => {
	resetForm(formRef.value);
};
/**
 * 重置表单
 */
const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	state.form.id = undefined;
	loading.value = false;
	dialog.value = false;
	formEl.resetFields();
};
/**
 * 提交按钮
 */
const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			loading.value = true;
			if (state.form.id) {
				//修改
				edit();
			} else {
				//新增
				add();
			}
		}
	});
};
/**
 * 新增
 */
const add = () => {
	addObj(state.form)
		.then(() => {
			resetForm(formRef.value);
			ElMessage.success('新增成功');

			emit('initPage');
		})
		.catch(() => {
			loading.value = false;
		});
};
/**
 * 修改
 */
const edit = () => {
	editObj(state.form)
		.then(() => {
			resetForm(formRef.value);
			ElMessage.success('修改成功');
			emit('initPage');
		})
		.catch(() => {
			loading.value = false;
		});
};
/**
 * 查询全部角色
 */
const handleRoleList = () => {
	getRoleList({}).then((response: any) => {
		state.roleList = response.data.data;
	});
};
/**
 * 上传前
 */
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
	if (rawFile.type !== 'image/jpeg') {
		ElMessage.error('Avatar picture must be JPG format!');
		return false;
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error('Avatar picture size can not exceed 2MB!');
		return false;
	}
	return true;
};
/**
 * 上传成功事件
 */
const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
	state.form.avatar = response.data;
};
/**
 * 上传失败事件
 */
const handleError: UploadProps['onError'] = (error) => {
	ElMessage.error(error + '');
};
const shopChange = (shop: any) => {
	state.form.shopName = shop.name;
};
/**
 * 查询全部部门
 */
const handleDeptList = () => {
	getTreeList()
		.then((response: any) => {
			state.deptList = response.data.data;
		})
		.catch(() => {});
};
defineExpose({
	initForm,
});
</script>
<style scoped>
.avatar-uploader .avatar {
	width: 140px;
	height: 140px;
	display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 26px;
	color: #8c939d;
	width: 140px;
	height: 140px;
	text-align: center;
}
</style>
